# -*- coding: utf-8 -*-
"""
基准回归 + 机制检验（一键 Python）
"""

import pandas as pd, numpy as np, statsmodels.api as sm
from linearmodels.panel import PooledOLS, PanelOLS
from linearmodels.iv import IV2SLS

# 读数
risk = pd.read_csv("outputs/risk_metrics.csv")
risk['year'] = risk['firm'].str.split("_").str[1].astype(int)
risk['firm'] = risk['firm'].str.split("_").str[0]

fin = pd.read_csv("data/csmar_fin.csv")  # 自己下 CSMAR
df = risk.merge(fin, on=['firm', 'year'], how='inner')

# 构造面板
df = df.set_index(['firm', 'year'])

# 1. 固定效应基准
controls = ['size', 'lev', 'roa', 'board_indr']  # 控制变量
formula = 'tobinq ~ digi_risk + ' + ' + '.join(controls)
mod_fe = PanelOLS.from_formula(formula + " + EntityEffects + TimeEffects", data=df)
res_fe = mod_fe.fit(cov_type='clustered', cluster_entity=True)
print(res_fe)

# 2. 工具变量 2SLS
formula_iv = 'tobinq ~ 1 + ' + ' + '.join(controls) + ' [digi_risk ~ IV_US]'
df = df.merge(pd.read_csv("outputs/iv_us.csv"), on=['sic2', 'year'])
mod_iv = IV2SLS.from_formula(formula_iv, data=df)
res_iv = mod_iv.fit(cov_type='clustered', clusters=df.index.get_level_values(0))
print(res_iv)

# 3. 机制检验
# 3.1 供应链溢出
tier1 = pd.read_csv("data/orbis_tier1.csv")  # BVD Orbis 上下游关系
df = df.reset_index().merge(tier1, on='firm')
df['tier1_tobinq'] = df.groupby(['year', 'tier1'])['tobinq'].transform('mean')
df = df.set_index(['firm', 'year'])
mod_chain = PanelOLS.from_formula('tier1_tobinq ~ digi_risk + size + lev + roa + EntityEffects', data=df)
print(mod_chain.fit())

# 3.2 声誉损害
df['reputation'] = df['analyst_following'] + df['media_pos']  # 代理变量示例
mod_rep = PanelOLS.from_formula('reputation ~ digi_risk + controls + EntityEffects', data=df)
print(mod_rep.fit())
